#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :new_attendance_page.py
# Time  :2025/5/27 15:37
# Email :fortunatedong@163.com
# Author:by Adonli
from datetime import datetime
import json
import time

import pandas as pd
import streamlit as st
import toml

from config import Header_space
from settings.attendance import load_current_staff_sort,save_current_staff_sort,sort_by_staff_asc,sort_by_department_asc
import os
from config import ROOT_DIR
from utils.hr_task.attendance import get_attendance_detail, load_attendance_file

current_attendance_dir = os.path.join(ROOT_DIR, 'Datas/hr_attendance')
configs_toml = os.path.join(ROOT_DIR, 'settings','configs.toml')
Header_space()
st.subheader("自动统计考勤表", divider=True)
today = datetime.today()
current_year = today.year
current_month = today.month
last_month = today.month - 1
col1, col2,col3,col4,col5 = st.columns([4,2,1,1,2])
with col1:
    uploaded_file = st.file_uploader(":blossom:**上传考勤原表**")
    if uploaded_file is not None:
        bytes_data = uploaded_file.getvalue()
        with open(configs_toml, "r", encoding="utf-8") as f:
            cfg = toml.load(f)
        cfg['HRTASK']['HRAttendanceName'] = uploaded_file.name
        with open(configs_toml, 'w', encoding="utf-8") as f:
            toml.dump(cfg, f)
        with open(f"{current_attendance_dir}/{uploaded_file.name}", "wb") as f:
            f.write(bytes_data)
with col2:
    st.write("\n")
    st.write("\n")
    month = st.number_input(":blossom:**输入统计的月份:**",min_value=0, max_value=12, value=last_month, step=1)
with col4:
    st.write("\n")
    st.write("\n")
    st.write("\n")
    button = st.button("执行")
if button:

    if uploaded_file is not None:
        current_df = load_attendance_file(f"{current_attendance_dir}/{uploaded_file.name}")
        get_attendance_detail(current_df,month)
        staff_sort_xlsx_path = f"{current_attendance_dir}/{current_year}考勤表.xlsx"
        df = pd.read_excel(staff_sort_xlsx_path, sheet_name=f"{current_year}年{month}月")
        st.data_editor(df)
        with col5:
            st.write("\n")
            st.write("\n")
            st.write("\n")
            with open(staff_sort_xlsx_path, "rb") as f:
                st.download_button(
                    label="下载Excel文件",
                    data=f,
                    file_name=f"{current_year}考勤表.xlsx",
                    mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
    else:
        st.warning("先上传考勤原表")